import requests
import datetime
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from sqlalchemy import create_engine, Column, Integer, String, JSON, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from apscheduler.schedulers.background import BackgroundScheduler
import atexit
from datetime import date

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "ok"}

# 配置数据库连接
engine = create_engine(
    "mysql+pymysql://enigma:YGM123456rds@rm-2ze9zw019dkj6tq3xho.mysql.rds.aliyuncs.com:3306/deal",
    connect_args={}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

# 定义数据模型
class Stock(Base):
    __tablename__ = "stocks"

    id = Column(Integer, primary_key=True, index=True)
    type = Column(String(255), nullable=False, comment='类型')
    stock = Column(String(100), nullable=False, comment='交易码')
    created_at = Column(DateTime, default=datetime.datetime.utcnow, comment='创建时间')

Base.metadata.create_all(bind=engine)

# 定义请求体模型
class StockOrder(BaseModel):
    type: str
    message: dict
    timestamp: str

@app.post("/stocks/sync")
async def sync(params: StockOrder):
    stocks = params.message.get("stocks", [])

    stocks_to_insert = []
    # 循环处理 stocks 列表
    for stock in stocks:
        # 这里可以添加你具体的处理逻辑，例如打印股票代码
        once_data = {
            "type": params.type,
            "stock": stock,
            "created_at": datetime.datetime.now()
        }
        stocks_to_insert.append(once_data)

    # 入库
    db = SessionLocal()
    try:
        today = date.today()
        # 删除当天的记录
        db.query(Stock).filter(Stock.created_at >= today,
                               Stock.created_at < date(today.year, today.month, today.day + 1)).delete()
        db.commit()

        for data in stocks_to_insert:
            db_stock = Stock(**data)
            db.add(db_stock)
        db.commit()
        return {"message": "Stock added successfully"}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        db.close()

# 定义请求参数模型
class TodayParams(BaseModel):
    # 可以根据实际需求添加其他参数
    pass

# 飞书 Webhook 地址
FEISHU_WEBHOOK_URL = "https://open.feishu.cn/open-apis/bot/v2/hook/71d4e24c-ffde-4393-85c3-c99afccb1f14"

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def check_stock_data():
    db = next(get_db())
    today = datetime.date.today()
    try:
        # 查询当天的数据
        stocks = db.query(Stock).filter(Stock.created_at >= datetime.datetime.combine(today, datetime.time.min),
                                        Stock.created_at < datetime.datetime.combine(today, datetime.time.max)).all()
        # 统计 stocks 的数量
        stock_count = len(stocks)

        if not stocks:
            # 若没有查询到数据，发送飞书 Webhook 请求
            headers = {
                'Content-Type': 'application/json'
            }
            data = {
                "msg_type": "text",
                "content": {
                    "text": "今日时间：" + str(today) + "统计数据量：" + str(stock_count)
                }
            }
            try:
                response = requests.post(FEISHU_WEBHOOK_URL, headers=headers, json=data)
                response.raise_for_status()
                print("今日时间：", today, "统计数据量：", stock_count)
            except requests.RequestException as err:
                print(f"飞书 Webhook 发送失败: {err}")
        else:
            print("今日时间：", today, "统计数据量：", stock_count)
    except Exception as e:
        print(f"数据库查询出错: {str(e)}")
    finally:
        db.close()

# 创建并启动定时任务
scheduler = BackgroundScheduler()
scheduler.add_job(func=check_stock_data, trigger='cron', hour=10)
scheduler.start()

@app.post("/stocks/check")
async def check():
    return check_stock_data()

# 在应用关闭时关闭调度器
atexit.register(lambda: scheduler.shutdown())